package com.sheep.dynamic.controller;

import com.sheep.dynamic.config.DynamicDataSourceConfig;
import com.sheep.dynamic.entity.DataSourceMeta;
import com.sheep.dynamic.service.DataSourceMetaService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * 数据源控制器
 *
 * @author 第七人格
 * @date 2023/04/13
 */
@RestController
@RequestMapping(value = "/data")
public class DataSourcesController {
    /**
     * 数据源元数据服务
     */
    @Resource
    private DataSourceMetaService dataSourceMetaService;

    /**
     * 动态数据源配置
     */
    @Resource
    private DynamicDataSourceConfig dynamicDatasourceConfig;

    /**
     * 添加
     *
     * @param meta 元
     * @return {@link Object}
     */
    @PostMapping("/add")
    public Object add(@RequestBody DataSourceMeta meta){
        try{
            dataSourceMetaService.add(meta);
            return "添加成功";
        }catch (Exception e){
            return "添加失败，"+e.getMessage();
        }
    }

    /**
     * 初始化数据库
     *
     * @param meta 元
     * @return {@link Object}
     */
    @PostMapping("/initDB")
    public Object initDB(@RequestBody DataSourceMeta meta){
        try{
            //建库
            if(dataSourceMetaService.initDB(meta)){
                //更新
                dataSourceMetaService.update(meta);
                //更新缓存
                dynamicDatasourceConfig.addDB(meta);
                return "数据库创建成功";
            }
            return "数据库创建失败，请确认MySQL信息";
        }catch (Exception e){
            return "数据库创建失败，"+e.getMessage();
        }
    }

    /**
     * 连接数据库
     *
     * @param meta 元
     * @return {@link Object}
     */
    @PostMapping("/connectDB")
    public Object connectDB(@RequestBody DataSourceMeta meta){
        if(dataSourceMetaService.tryConnectDB(meta)){
            return "数据库连接正常";
        }
        return "数据库连接失败，请确认MySQL信息后尝试重建数据库";
    }

    /**
     * 删除
     *
     * @param meta 元
     * @return {@link Object}
     */
    @PostMapping("/delete")
    public Object delete(@RequestBody DataSourceMeta meta){
        try{
            dataSourceMetaService.delete(meta.getId());
            //删库
            dynamicDatasourceConfig.deleteDB(meta);
            return "删除成功";
        }catch (Exception e){
            return "删除失败，"+e.getMessage();
        }
    }
}
